#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: redis_utils.py
@time: 2023/11/8 11:03
@desc: 
"""
import redis
from backend.conf.config import redis_options


class RedisBase(object):
    redis_tool = None

    @classmethod
    def TestConn(cls):
        if not cls.redis_tool:
            pool = redis.ConnectionPool(host=redis_options.get("redis_host"), port=redis_options.get("redis_port"),
                                        db=redis_options.get("redis_db"),
                                        password=redis_options.get("redis_password"),
                                        username=redis_options.get("redis_username"),
                                        decode_responses=True)
            cls.redis_tool = redis.Redis(connection_pool=pool)

    @classmethod
    def get(cls, key):
        cls.TestConn()
        return cls.redis_tool.get(key)

    @classmethod
    def set(cls, key, target, expire_time):
        cls.TestConn()
        cls.redis_tool.set(key, target, ex=expire_time)

    @classmethod
    def expire_seconds(cls, key):
        cls.TestConn()
        # 查询某个键的剩余时间
        return cls.redis_tool.ttl(key)

    @classmethod
    def keys(cls):
        cls.TestConn()
        return cls.redis_tool.keys()

    @classmethod
    def delete(cls, key):
        cls.TestConn()
        cls.redis_tool.delete(key)

    @classmethod
    def exists(cls, key):
        cls.TestConn()
        return cls.redis_tool.exists(key)


    @classmethod
    def hset(cls, key, target, expire_time):
        cls.TestConn()
        cls.redis_tool.hset(key, target, ex=expire_time)

